package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.function.Consumer;

@Slf4j
public class TailCommand {
    private Session sshSession;

    public TailCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public void exec(int lines, String logFile, Consumer<String> consumer) {
        ChannelExec channelExec = null;
        BufferedReader input = null;
        try {
            channelExec = (ChannelExec) sshSession.openChannel("exec");
            String command = "tail -f -n " + lines + " " + logFile;
            channelExec.setCommand(command);
            channelExec.connect();
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));

            String line;
            while ((line = input.readLine()) != null) {
                consumer.accept(line);
            }
        } catch (Exception e) {
            log.error("tail  err:{}", e.getMessage());
            throw new RuntimeException("tail close");
        } finally {
            try {
                if (input != null) input.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
    }


}

